package com.yc.servlet;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.yc.bean.*;
import com.yc.dao.DinnerTableDao;
import com.yc.dao.FoodDao;
import com.yc.dao.UserDao;
import com.yc.model.JsonModel;
import com.yc.util.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.UUID;

@WebServlet("/fooddetail")
@MultipartConfig
public class FoodDetailServlet extends BaseServlet {
    // OSS 配置信息
    private static final String endpoint = "https://oss-cn-beijing.aliyuncs.com"; // OSS 外网节点或自定义域名
    private static final String accessKeyId = "LTAI5tMaMpqNrQHS5ums69Mr";
    private static final String accessKeySecret = "qrCGpsNCirvOSM8wrhnj97hSMO41qw";
    private static final String bucketName = "daiwei001";
    public void getfooddetail(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    String foodid=req.getParameter("foodid");


        JsonModel jm=new JsonModel();
        List<FoodDetailBean> finddetail = FoodDao.finddetail(Integer.parseInt(foodid));

        if (!finddetail.isEmpty()){
            jm.setCode(1);
            jm.setObj(finddetail.get(0));
        }else {
            jm.setCode(0);
        }
        super.writeJson(jm,resp);
    }
    public void getreview(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String foodid=req.getParameter("foodid");


        JsonModel jm=new JsonModel();
        List<ReviewBean> finddetail = FoodDao.findreview(Integer.parseInt(foodid));

        if (!finddetail.isEmpty()){
            jm.setCode(1);
            jm.setObj(finddetail);
        }else {
            jm.setCode(0);
        }
        super.writeJson(jm,resp);
    }
    public void getfoodbyid(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String foodid=req.getParameter("foodid");


        JsonModel jm=new JsonModel();
        List<FoodBean> foodBeans = FoodDao.find(Integer.parseInt(foodid));

        if (!foodBeans.isEmpty()){
            jm.setCode(1);
            jm.setObj(foodBeans.get(0));
        }else {
            jm.setCode(0);
        }
        super.writeJson(jm,resp);
    }
    public void getuser(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        JsonModel jm=new JsonModel();
        List<UserBean> userBeans = UserDao.find();

        if (!userBeans.isEmpty()){
            jm.setCode(1);
            jm.setObj(userBeans);
        }else {
            jm.setCode(0);
        }
        super.writeJson(jm,resp);
    }
    public void addReviews(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Part filePart = req.getPart("review_image"); // 获取上传的文件部分
        JsonModel jm = new JsonModel();

        ReviewBean reviews = null;
        try {
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (filePart != null && filePart.getSize() > 0) {
            String fileName = filePart.getSubmittedFileName();
            InputStream fileContent = filePart.getInputStream(); // 获取文件内容
            String uuid = UUID.randomUUID().toString().replaceAll("-", ""); // 生成唯一的文件名
            String objectName = uuid + "_" + fileName;

            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 初始化OSS客户端
            try {
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentLength(filePart.getSize());
                ossClient.putObject(bucketName, objectName, fileContent, metadata); // 上传文件到OSS
                String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
                System.out.println(url); // 打印文件URL


                String foodid = req.getParameter("foodid");
                String star = req.getParameter("star");
                String reviewText = req.getParameter("review_text");
                String userid=req.getParameter("userid");
                // 插入数据库
                Boolean rs = FoodDao.insertReview(Integer.parseInt(userid), Integer.parseInt(foodid), reviewText, url, Integer.parseInt(star));

                if (rs) {
                    jm.setCode(1);
                } else {
                    jm.setCode(0);
                }
                super.writeJson(jm, resp);
            } finally {
                ossClient.shutdown(); // 关闭OSS客户端
            }
        } else {
            String foodid = req.getParameter("foodid");
            String star = req.getParameter("star");
            String reviewText = req.getParameter("review_text");
            String userid=req.getParameter("userid");

            // 如果文件为空，仍然执行数据插入操作
            Boolean rs = FoodDao.insertReview(Integer.parseInt(userid), Integer.parseInt(foodid), reviewText, "", Integer.parseInt(star));

            if (rs) {
                jm.setCode(1);
            } else {
                jm.setCode(0);
            }
            super.writeJson(jm, resp);

            System.out.println("No file uploaded or file is empty."); // 可以记录日志，不需要向用户返回错误
        }
    }

    public void addReplies(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Part filePart = req.getPart("reply_image"); // 获取上传的文件部分
        JsonModel jm = new JsonModel();

        ReviewBean reviews = null;
        try {
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (filePart != null && filePart.getSize() > 0) {
            String fileName = filePart.getSubmittedFileName();
            InputStream fileContent = filePart.getInputStream(); // 获取文件内容
            String uuid = UUID.randomUUID().toString().replaceAll("-", ""); // 生成唯一的文件名
            String objectName = uuid + "_" + fileName;

            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 初始化OSS客户端
            try {
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentLength(filePart.getSize());
                ossClient.putObject(bucketName, objectName, fileContent, metadata); // 上传文件到OSS
                String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
                System.out.println(url); // 打印文件URL


                String reviewid = req.getParameter("reviewid");
                String replyText = req.getParameter("replyText");
                String userid=req.getParameter("userid");
                // 插入数据库
                Boolean rs = FoodDao.insertReplies(Integer.parseInt(reviewid), Integer.parseInt(userid), replyText, url);

                if (rs) {
                    jm.setCode(1);
                } else {
                    jm.setCode(0);
                }
                super.writeJson(jm, resp);
            } finally {
                ossClient.shutdown(); // 关闭OSS客户端
            }
        } else {

            String reviewid = req.getParameter("reviewid");
            String replyText = req.getParameter("replyText");
            String userid=req.getParameter("userid");

            // 如果文件为空，仍然执行数据插入操作
            Boolean rs = FoodDao.insertReplies(Integer.parseInt(reviewid), Integer.parseInt(userid), replyText, "");

            if (rs) {
                jm.setCode(1);
            } else {
                jm.setCode(0);
            }
            super.writeJson(jm, resp);

            System.out.println("No file uploaded or file is empty."); // 可以记录日志，不需要向用户返回错误
        }
    }

    public void getReplies(HttpServletRequest req, HttpServletResponse resp) throws Exception {

        JsonModel jm=new JsonModel();
        List<RepliesBean> rs = FoodDao.findreplies();

            if (!rs.isEmpty()){
                jm.setCode(1);
                jm.setObj(rs);
            }else {
                jm.setCode(0);
            }
            super.writeJson(jm,resp);
    }
    public void occupancy(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JsonModel jm=new JsonModel();
        String tableid=req.getParameter("tableid");
        Boolean rs = DinnerTableDao.occupancy(Integer.parseInt(tableid));
        if (rs){
            jm.setCode(1);
        }else {
            jm.setCode(0);
        }
        super.writeJson(jm,resp);
    }
    public void release(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JsonModel jm=new JsonModel();
        String tableid=req.getParameter("tableid");
        Boolean rs = DinnerTableDao.release(Integer.parseInt(tableid));
        if (rs){
            jm.setCode(1);
        }else {
            jm.setCode(0);
        }
        super.writeJson(jm,resp);
    }
}
